package com.danskin.wechat.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

public class FileUploadUtil {

	// private static final String IMAGE_URL = "http://img.puman.cn/api/upload";

	@SuppressWarnings("unused")
	private static final String GET = "GET";
	private static final String POST = "POST";
	private static String CHARSET = "UTF-8";
	private static String BOUNDARY = "---------------------------123821742118716"; // boundary就是request头和上传文件内容的分隔符

	public static String imageUpload(String url, File image, Map<String, String> queryParams,
			Map<String, String> formParams, String fileKey, String contentType) {

		HttpURLConnection conn = null;
		try {
			conn = getHttpConnection(buildUrlWithQueryString(url, queryParams), POST, null);
			conn.connect();

			OutputStream out = conn.getOutputStream();

			/**
			 * 参数
			 */
			StringBuffer sb = new StringBuffer();
			if (formParams != null && !formParams.isEmpty()) {
				for (Entry<String, String> entry : formParams.entrySet()) {

					sb.append("\r\n--").append(BOUNDARY).append("\r\n");
					sb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"\r\n\r\n")
							.append(entry.getValue());
				}
			}

			sb.append("\r\n--").append(BOUNDARY).append("\r\n");
			sb.append("Content-Disposition: form-data; name=\"" + fileKey + "\"; filename=\"" + image.getName()
					+ "\"\r\n").append("Content-Type: " + contentType + "\r\n\r\n");
			out.write(sb.toString().getBytes());
			// System.out.println(sb.toString());

			FileInputStream fis = new FileInputStream(image);

			byte[] temp = new byte[1024 * 1024];
			int len;

			while ((len = fis.read(temp)) != -1) {
				out.write(temp, 0, len);
				out.flush();
			}

			String end = "\r\n--" + BOUNDARY + "--\r\n\r\n";

			out.write(end.getBytes());

			// System.out.println(end);
			out.flush();
			out.close();
			fis.close();

			return readResponseString(conn);
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			if (conn != null) {
				conn.disconnect();
			}
		}
	}

	/**
	 * Build queryString of the url
	 */
	private static String buildUrlWithQueryString(String url, Map<String, String> queryParas) {
		if (queryParas == null || queryParas.isEmpty())
			return url;

		StringBuilder sb = new StringBuilder(url);
		boolean isFirst;
		if (url.indexOf("?") == -1) {
			isFirst = true;
			sb.append("?");
		} else {
			isFirst = false;
		}

		for (Entry<String, String> entry : queryParas.entrySet()) {
			if (isFirst)
				isFirst = false;
			else
				sb.append("&");

			String key = entry.getKey();
			String value = entry.getValue();
			if (StringUtil.notBlank(value))
				try {
					value = URLEncoder.encode(value, CHARSET);
				} catch (UnsupportedEncodingException e) {
					throw new RuntimeException(e);
				}
			sb.append(key).append("=").append(value);
		}
		return sb.toString();
	}

	private static HttpURLConnection getHttpConnection(String url, String method, Map<String, String> headers)
			throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
		URL _url = new URL(url);
		HttpURLConnection conn = (HttpURLConnection) _url.openConnection();

		conn.setRequestMethod(method);
		conn.setDoOutput(true);
		conn.setDoInput(true);

		conn.setConnectTimeout(19000);
		conn.setReadTimeout(19000);

		conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
		conn.setRequestProperty("User-Agent",
				"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36");

		if (headers != null && !headers.isEmpty())
			for (Entry<String, String> entry : headers.entrySet())
				conn.setRequestProperty(entry.getKey(), entry.getValue());

		return conn;
	}

	private static String readResponseString(HttpURLConnection conn) {
		StringBuilder sb = new StringBuilder();
		InputStream inputStream = null;
		try {
			inputStream = conn.getInputStream();
			BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, CHARSET));
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line).append("\n");
			}
			return sb.toString();
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					// LogKit.error(e.getMessage(), e);
				}
			}
		}
	}

	public static void main(String[] args) {
		File image = new File("D:\\1.jpg");
		Map<String, String> queryParas = new HashMap<String, String>();
		queryParas.put("access_token",
				"b7Hl8_rQTEUbBKf-HYO8rqzA5o-69iKw8-UlSMsDwxQNA-0vm8PLXhTic1txU8lF0TdfJKxhzzTyG1Td5Fi5KfHaw1L1GrjoKC50uZggfW6_csSqlgsmkL7hG7j5D0hqKZRjALDXME");
		queryParas.put("type", "image");
		String imageUpload = imageUpload("https://api.weixin.qq.com/cgi-bin/material/add_material", image, queryParas,
				null, "media", "image/jpeg");
		System.out.println("result:" + imageUpload);
	}
}
